/*
 * @Date: 2022-05-16 14:32:21
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-05-17 10:14:30
 * @FilePath: \react-lvyou\src\store\user\index.ts
 * @Description: something
 */
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";

interface UserState {
  loading: boolean;
  token: string | null;
}
export const fetchUserReqLogin = createAsyncThunk(
  "UserSlice/userReqLogin",
  async (
    paramaters: {
      username: string;
      password: string;
    },
    thunkAPI,
  ) => {
    const { data } = await axios.post(`http://123.56.149.216:8089/auth/login`, {
      email: paramaters.username,
      password: paramaters.password,
    });
    return data.token;
  },
);
const initialState: UserState = {
  loading: false,
  token: null,
};
export const UserSlice = createSlice({
  name: "UserSlice",
  initialState,
  reducers: {
    logout: (state) => {
      state.token = null;
      state.loading = false;
    },
  },
  extraReducers: {
    [fetchUserReqLogin.pending.type]: (state) => {
      state.loading = true;
    },
    [fetchUserReqLogin.fulfilled.type]: (state, action) => {
      state.loading = false;
      state.token = action.payload;
    },
    [fetchUserReqLogin.rejected.type]: (state) => {
      state.loading = false;
    },
  },
});
